/**
 * Created by wanthering on 2017/8/18.
 */
'use strict'
const jwt = require('jwt-simple');
const config = require('../../config/config')
const Promise = require('bluebird')
const axios = require('axios')
const mongoose = require('mongoose');
const Student = mongoose.model('Student');
const Lesson = mongoose.model('Lesson');
const Article = mongoose.model('Article');
const moment = require('moment')

exports.login = async function(ctx, next){

  let phone = ctx.request.body.phone
  let _id = ctx.request.body._id


  let studentEntity = await Student.findOne({phone})

  if(studentEntity){

    //之前有答完题没领红包的情况

    let notGottenPack
    let alreadyGotTodayPack = false;
    if(studentEntity.lastAwardTime){
      alreadyGotTodayPack = moment(studentEntity.lastAwardTime).format('l')===moment().format('l')
    }

    let totalAward = 0
    let recentLessonId

    if(studentEntity.lesson && studentEntity.lesson.length>0){
      for(let l of studentEntity.lesson){
        totalAward += l.award
        recentLessonId = l._id
        if(l._id.toString() === _id.toString()){
          if(l.answered && !l.withdrew){
            notGottenPack = true
          }
        }
      }
    }

    let article = ''
    let articleEntity = await Article.findOne({lesson:_id,phone:phone})
    if(articleEntity){
      article = articleEntity.article
    }

    let recentLesson = {}
    if(recentLessonId){
      let recentLessonEntity = await Lesson.findOne({_id:recentLessonId})
      recentLesson._id = recentLessonEntity._id
      recentLesson.title = recentLessonEntity.title
    }


    let payload = { phone };
    let secret  = config.secret
    let token = jwt.encode(payload, secret);

    let returnAward = calAward(studentEntity,_id)

    ctx.body = {
      success:true,
      token,
      award:returnAward,
      notGottenPack,
      alreadyGotTodayPack,
      totalAward,
      recentLesson,
      article
    }

  }else{

    //没有登录过的情况

    let {data} = await axios.post('https://biz-op.rijin.com/api/bridge/checkAccountExist',{
      phone
    })
    if(data.success){
      if(data.registered){
        studentEntity= new Student({
          phone,
          registered:true
        })

        console.log('首次登录，且已经注册日日进')

      }else {
        studentEntity = new Student({
          phone,
          registered: false
        })

        console.log('首次登录，且没有注册日日进')
      }
      await studentEntity.save()
      let payload = { phone };
      let secret  = config.secret
      let token = jwt.encode(payload, secret);
      ctx.body = {
        success:true,
        token,
        award:config.award[0]
      }

    }else{
      ctx.body={
        success:false,
        errMsg:10000
      }
    }
  }
}

exports.autoLogin = async function(ctx, next){
  let token = ctx.request.body.token
  let payload = jwt.decode(token,config.secret,true);
  let phone = payload.phone
  let _id = ctx.request.body._id
  console.log('phone:'+phone)

  let studentEntity = await Student.findOne({phone})
  if(studentEntity){
    let notGottenPack = false;
    let alreadyGotTodayPack = false;
    if(studentEntity.lastAwardTime){
      alreadyGotTodayPack = moment(studentEntity.lastAwardTime).format('l')===moment().format('l')
    }

    let article = ''
    let articleEntity = await Article.findOne({lesson:_id,phone:phone})
    if(articleEntity){
      article = articleEntity.article
    }

    let totalAward = 0
    let recentLessonId

    if(studentEntity.lesson && studentEntity.lesson.length>0){
      for(let l of studentEntity.lesson){
        totalAward += l.award
        recentLessonId = l._id
        if(l._id.toString() === _id.toString()){
          if(l.answered && !l.withdrew){
            notGottenPack = true
          }
        }
      }
    }

    let recentLesson = {}
    if(recentLessonId){
      let recentLessonEntity = await Lesson.findOne({_id:recentLessonId})
      recentLesson._id = recentLessonEntity._id
      recentLesson.title = recentLessonEntity.title
    }

    //之前有登录过的情况

    let payload = { phone };
    let secret  = config.secret
    let token = jwt.encode(payload, secret);
    let returnAward = calAward(studentEntity,_id)

    ctx.body = {
      success:true,
      token,
      phone,
      award:returnAward,
      notGottenPack,
      alreadyGotTodayPack,
      totalAward,
      recentLesson,
      article
    }

  }else{
    ctx.body = {
      success:false,
      errMsg:10001,
    }
  }
}


exports.answerRight = async function(ctx, next) {
  let _id = ctx.request.body._id
  let token = ctx.request.body.token
  let payload = jwt.decode(token, config.secret, true);
  let phone = payload.phone

  let studentEntity = await Student.findOne({phone})

  if(!studentEntity){
    ctx.body = {
      success:false,
      errMsg:10003
    }
    return
  }

  let alreadyGotTodayPack = false;
  if(studentEntity.lastAwardTime){
    alreadyGotTodayPack = moment(studentEntity.lastAwardTime).format('l')===moment().format('l')
  }

  if(alreadyGotTodayPack){
    ctx.body = {
      success:false,
      errMsg:10009
    }
    return
  }


  let returnAward = calAward(studentEntity,_id)
  if(studentEntity.lesson){
    let haveThisLesson = false;
    for(let l of studentEntity.lesson){
      if(l._id.toString() === _id.toString()){
        haveThisLesson = true;
      }
    }

    if(!haveThisLesson){
      studentEntity.lesson.push(
        {_id,award:returnAward,answered:true,withdrew:false}
      )
    }
  }else{
    //如果没有过lesson，则创建
    studentEntity.lesson = [
      {_id,award:returnAward,answered:true,withdrew:false}
    ]
  }
  await studentEntity.save()

  ctx.body={
    success:true
  }

}


function calAward(studentEntity,_id){
  let returnAward
  if(!_id){
    if(!studentEntity.lesson){
      returnAward = config.award[0]

      console.log('有过登录记录，且没有领到过奖励')
    }else{
      if(studentEntity.lesson.length === 0){
        returnAward = config.award[0]
      } else if(studentEntity.lesson.length >= 1 && studentEntity.lesson.length<=8){
        let l = studentEntity.lesson.length
        returnAward = config.award[l]
      } else if(studentEntity.lesson.length >9){
        let l = studentEntity.lesson.length
        if(l%3===0){
          returnAward = 7.18
        }if(l%3===1){
          returnAward = 9.18
        }if(l%3===2){
          returnAward = 6.18
        }
      }
      console.log('有过登录记录，且已经领到过奖励，即将领奖励:'+returnAward+'元')
    }
  }else{
    if(!studentEntity.lesson){
      returnAward = config.award[0]

      console.log('有过登录记录，且没有领到过奖励')
    }else{
      for (let l of studentEntity.lesson){
        if(l._id.toString() === _id.toString()){
          returnAward = l.award
        }
      }
      if(!returnAward){
        if(studentEntity.lesson.length === 0){
          returnAward = config.award[0]
        } else if(studentEntity.lesson.length >= 1 && studentEntity.lesson.length<=8){
          let l = studentEntity.lesson.length
          returnAward = config.award[l]
        } else if(studentEntity.lesson.length >9){
          let l = studentEntity.lesson.length
          if(l%3===0){
            returnAward = 7.18
          }if(l%3===1){
            returnAward = 9.18
          }if(l%3===2){
            returnAward = 6.18
          }
        }
      }


    }
  }
  return returnAward
}


exports.withdraw = async function(ctx, next) {
  let _id = ctx.request.body._id
  let token = ctx.request.body.token
  let payload = jwt.decode(token,config.secret,true);
  let phone = payload.phone

  //情况1： 检测到没有注册，推出注册页面

  let {data} = await axios.post('https://biz-op.rijin.com/api/bridge/checkAccountExist',{
    phone
  })

  if(!data.success){
    ctx.body = {
      success: false,
      errMsg: 10002
    }
    return;
  }

  if(!data.registered){
    ctx.body = {
      success:true,
      notRegistered:true
    }
    return
  }

  //查询是否已经进行过本次活动领取过了体验金
  let studentEntity = await Student.findOne({phone})
  if(!studentEntity){
    ctx.body = {
      success:false,
      errMsg:10004
    }
    return
  }

  let alreadyGotTodayPack = false;
  if(studentEntity.lastAwardTime){
    alreadyGotTodayPack = moment(studentEntity.lastAwardTime).format('l')===moment().format('l')
  }

  if(alreadyGotTodayPack){
    ctx.body ={
      success:false,
      errMsg:10009
    }
    return
  }

  if(!studentEntity.lesson && studentEntity.lesson.length===0){
    ctx.body ={
      success:false,
      errMsg:10005
    }
    return
  }

  let haveThisLesson = false
  let canWithdraw = false
  let award

  for (let l of studentEntity.lesson){
    if(l._id.toString() === _id.toString()){
      haveThisLesson = true
      if(l.answered && !l.withdrew){
        canWithdraw = true
        award = l.award
      }
    }
  }
  if(!haveThisLesson){
    ctx.body ={
      success:false,
      errMsg:10005
    }
    return
  }

  if(canWithdraw){

    let reqData
    if(award === 0.88){
      let {data} = await axios.post('https://biz-op.rijin.com/api/bridge/sendCoupon',{
        coupon:'EC20170918182006428',
        type:'experience',
        token:token,
        key:config.key
      })
      reqData = data.reqData
    }else if(award===10.88){

      let {data} = await axios.post('https://biz-op.rijin.com/api/bridge/sendCoupon',{
        coupon:'EC20170918182240118',
        type:'cash',
        token:token,
        key:config.key
      })
      reqData = data.reqData


    }else if(award===5.18){

      let {data} = await axios.post('https://biz-op.rijin.com/api/bridge/sendCoupon',{
        coupon:'EC20170918182339697',
        type:'cash',
        token:token,
        key:config.key
      })
      reqData = data.reqData

    }else if(award===8.18){


      let {data} = await axios.post('https://biz-op.rijin.com/api/bridge/sendCoupon',{
        coupon:'EC20170918182432773',
        type:'cash',
        token:token,
        key:config.key
      })
      reqData = data.reqData

    }else if(award===9.18){

      let {data} = await axios.post('https://biz-op.rijin.com/api/bridge/sendCoupon',{
        coupon:'EC20170918182530872',
        type:'cash',
        token:token,
        key:config.key
      })
      reqData = data.reqData

    }else if(award===7.18){

      let {data} = await axios.post('https://biz-op.rijin.com/api/bridge/sendCoupon',{
        coupon:'EC20170918182651359',
        type:'cash',
        token:token,
        key:config.key
      })
      reqData = data.reqData

    }else if(award===12.18){

      let {data} = await axios.post('https://biz-op.rijin.com/api/bridge/sendCoupon',{
        coupon:'EC20170918182804196',
        type:'cash',
        token:token,
        key:config.key
      })
      reqData = data.reqData

    }


    //验证reqData正确性
    if(!reqData){
      ctx.body={
        success:false,
        errMsg:10006
      }
      return
    }
    let req = JSON.parse(reqData)
    if(req.code !== 0 ){
      ctx.body={
        success:false,
        errMsg:10007
      }
      return
    }

    for (let l of studentEntity.lesson){
      if(l._id.toString() === _id.toString()){
        l.withdrew = true
      }
    }
    studentEntity.lastAwardTime = new Date()
    await studentEntity.save()

    ctx.body = {
      success:true,
      sendCouponSuccess:true
    }
  }else{
    ctx.body = {
      success:true,
      sendCouponSuccess:false,
      alreadyGotten:true
    }
  }
}

exports.withdrawRd = async function(ctx, next) {
  let _id = ctx.request.body._id
  let token = ctx.request.body.token
  let payload = jwt.decode(token,config.secret,true);
  let phone = payload.phone

  //情况1： 检测到没有注册，推出注册页面

  let {data} = await axios.post('https://biz-op.rijin.com/api/bridge/checkAccountExist',{
    phone
  })

  if(!data.success){
    ctx.body = {
      success: false,
      errMsg: 10002
    }
    return;
  }

  if(!data.registered){
    ctx.body = {
      success:true,
      notRegistered:true
    }
    return
  }

  //查询是否已经进行过本次活动领取过了体验金
  let studentEntity = await Student.findOne({phone})
  if(!studentEntity){
    ctx.body = {
      success:false,
      errMsg:10004
    }
    return
  }

  let alreadyGotTodayPack = false;
  if(studentEntity.lastAwardTime){
    alreadyGotTodayPack = moment(studentEntity.lastAwardTime).format('l')===moment().format('l')
  }

  if(alreadyGotTodayPack){
    ctx.body ={
      success:false,
      errMsg:10009
    }
    return
  }

  if(!studentEntity.lesson && studentEntity.lesson.length===0){
    ctx.body ={
      success:false,
      errMsg:10005
    }
    return
  }

  let haveThisLesson = false
  let canWithdraw = false
  let award

  for (let l of studentEntity.lesson){
    if(l._id.toString() === _id.toString()){
      haveThisLesson = true
      if(l.answered && !l.withdrew){
        canWithdraw = true
        award = l.award
      }
    }
  }
  if(!haveThisLesson){
    ctx.body ={
      success:false,
      errMsg:10005
    }
    return
  }

  if(canWithdraw){

    let reqData
    if(award === 0.88){
      let {data} = await axios.post('https://biz-op.rijin.com/api/bridge/sendCoupon',{
        coupon:'EC20170918083223421',
        type:'experience',
        token:token,
        key:config.key
      })
      reqData = data.reqData
    }else if(award===10.88){

      let {data} = await axios.post('https://biz-op.rijin.com/api/bridge/sendCoupon',{
        coupon:'EC20170918083818384',
        type:'cash',
        token:token,
        key:config.key
      })
      reqData = data.reqData


    }else if(award===5.18){

      let {data} = await axios.post('https://biz-op.rijin.com/api/bridge/sendCoupon',{
        coupon:'EC20170918083948791',
        type:'cash',
        token:token,
        key:config.key
      })
      reqData = data.reqData

    }else if(award===8.18){


      let {data} = await axios.post('https://biz-op.rijin.com/api/bridge/sendCoupon',{
        coupon:'EC20170918084140765',
        type:'cash',
        token:token,
        key:config.key
      })
      reqData = data.reqData

    }else if(award===9.18){

      let {data} = await axios.post('https://biz-op.rijin.com/api/bridge/sendCoupon',{
        coupon:'EC20170918084352943',
        type:'cash',
        token:token,
        key:config.key
      })
      reqData = data.reqData

    }else if(award===7.18){

      let {data} = await axios.post('https://biz-op.rijin.com/api/bridge/sendCoupon',{
        coupon:'EC20170918091341219',
        type:'cash',
        token:token,
        key:config.key
      })
      reqData = data.reqData

    }else if(award===12.18){

      let {data} = await axios.post('https://biz-op.rijin.com/api/bridge/sendCoupon',{
        coupon:'EC20170918091508188',
        type:'cash',
        token:token,
        key:config.key
      })
      reqData = data.reqData

    }


    //验证reqData正确性
    if(!reqData){
      ctx.body={
        success:false,
        errMsg:10006
      }
      return
    }
    let req = JSON.parse(reqData)
    if(req.code !== 0 ){
      ctx.body={
        success:false,
        errMsg:10007
      }
      return
    }

    for (let l of studentEntity.lesson){
      if(l._id.toString() === _id.toString()){
        l.withdrew = true
      }
    }
    studentEntity.lastAwardTime = new Date()
    await studentEntity.save()

    ctx.body = {
      success:true,
      sendCouponSuccess:true
    }
  }else{
    ctx.body = {
      success:true,
      sendCouponSuccess:false,
      alreadyGotten:true
    }
  }
}


exports.sendArticle = async function(ctx, next){
  let _id = ctx.request.body._id
  let token = ctx.request.body.token
  let article = ctx.request.body.article


  if(!_id || !token){
    ctx.body={
      success:false,
      errMsg:10006
    }
    return;
  }
  let payload = jwt.decode(token,config.secret,true);
  let phone = payload.phone
  if(!phone){
    ctx.body={
      success:false,
      errMsg:10007
    }
    return;
  }

  if(!article || article.trim()===''){
    ctx.body={
      success:false,
      errMsg:10008
    }
    return;
  }


  let articleEntity = await Article.findOne({lesson:_id,phone:phone})
  if(!articleEntity){
    articleEntity = new Article({
      lesson:_id,
      phone,
      article
    })
  }else{
    articleEntity.article = article
  }

  await articleEntity.save()
  ctx.body = {
    success:true
  }

}